package com.meichis.yndms.dialog;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import androidx.core.content.FileProvider;

import com.meichis.mcsappframework.R;
import com.meichis.mcsappframework.entity.Attachment;
import com.meichis.mcsappframework.http.DONERESULT.ERRORCODE;
import com.meichis.mcsappframework.http.MCSWebDownLoadProvider;
import com.meichis.mcsappframework.http.MCSWebDownLoadProvider.MODCallback;
import com.meichis.mcsappframework.utils.ActivityUtils;
import com.meichis.mcsappframework.utils.SharePreferenceUtil;
import com.meichis.mcsappframework.utils.Tools;
import com.meichis.mcsappframework.utils.UniversalInterface;
import com.meichis.yndms.model.AppVersion;

import java.io.File;

public class AppUpdateDialog extends AlertDialog implements OnClickListener {

    private TextView tv_Cversion, tv_Sversion, txt_about, tv_upMessage;
    private Button bt_noupdate, bt_update;
    private Context dcontext;

    private ProgressDialog mydownDialog;
    private int PBDown = 0;
    private AppVersion appversion;
    private Attachment att;
    private Boolean ISCanCel = false;
    private TextView tv_title;

    private UniversalInterface<Void, Void> notUpdate;


    public AppUpdateDialog(Context context, AppVersion appVersion, UniversalInterface<Void, Void> notUpdate) {
        super(context, R.style.Appupdatedialog);
        dcontext = context;
        this.notUpdate = notUpdate;
        appversion = appVersion;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_versioninfo);
        try {
            this.dismiss();
        } catch (Exception e) {
        }
        initView();
    }

    /**
     * 设置标题和按钮的背景
     *
     * @param background
     */
    public void setDefaultBackground(Drawable background) {
        tv_title.setBackground(background);
        bt_update.setBackground(background);
        bt_noupdate.setBackground(background);
    }

    /**
     * 设置标题和按钮的背景
     *
     * @param resid
     */
    public void setDefaultBackground(int resid) {
        tv_title.setBackgroundResource(resid);
        bt_update.setBackgroundResource(resid);
        bt_noupdate.setBackgroundResource(resid);
    }

    /**
     * 单独设置标题背景
     *
     * @param background
     */
    public void setTitleBackground(Drawable background) {
        tv_title.setBackground(background);
    }

    /**
     * 单独设置标题背景
     *
     * @param resid
     */
    public void setTitleBackground(int resid) {
        tv_title.setBackgroundResource(resid);
    }

    /**
     * 单独设置按钮背景
     *
     * @param background
     */
    public void setButtonBackground(Drawable background) {
        bt_update.setBackground(background);
        bt_noupdate.setBackground(background);
    }

    /**
     * 单独设置按钮背景
     *
     * @param resid
     */
    public void setButtonBackground(int resid) {
        bt_update.setBackgroundResource(resid);
        bt_noupdate.setBackgroundResource(resid);
    }

    /**
     * 设置标题字体颜色
     *
     * @param color
     */
    public void setTitleTextColor(int color) {
        tv_title.setTextColor(color);
    }

    public void setButtonTextColor(int color) {
        bt_update.setTextColor(color);
        bt_noupdate.setTextColor(color);
    }

    private void initView() {
        tv_Cversion = (TextView) findViewById(R.id.tv_Cversion);
        tv_Sversion = (TextView) findViewById(R.id.tv_Sversion);
        txt_about = (TextView) findViewById(R.id.txt_about);
        tv_upMessage = (TextView) findViewById(R.id.tv_upMessage);

        tv_title = (TextView) findViewById(R.id.tv_title);

        bt_update = (Button) findViewById(R.id.bt_update);
        bt_update.setOnClickListener(this);
        bt_noupdate = (Button) findViewById(R.id.bt_noupdate);
        bt_noupdate.setOnClickListener(this);
        int localVersion = 0;
        try {
            PackageInfo packageInfo = dcontext.getApplicationContext().getPackageManager().getPackageInfo(dcontext.getPackageName(), 0);
            localVersion = packageInfo.versionCode;
            tv_Cversion.setText("V" + packageInfo.versionName);
            if (appversion != null) {
                tv_Sversion.setText("V" + appversion.getVersionName());
                if (appversion.getCurrentVersion() > localVersion) {
                    tv_Sversion.setTextColor(dcontext.getResources().getColor(R.color.red));
                }
                txt_about.setText(appversion.getPublishRemark());
                if (appversion.getMiniVersion() > localVersion && appversion.getCurrentVersion() > localVersion) {
                    tv_upMessage.setText(R.string.appupdate_Message1);
                    bt_update.setText(R.string.appupdate_update1);
                    bt_noupdate.setVisibility(View.GONE);
                } else if (appversion.getCurrentVersion() > localVersion) {
                    tv_upMessage.setText(R.string.appupdate_Message2);
                    bt_update.setText(R.string.appupdate_update2);
                    bt_noupdate.setText(R.string.appupdate_update3);
                }
                if (localVersion >= appversion.getCurrentVersion()) {
                    tv_upMessage.setText(R.string.appupdate_Message3);
                    bt_update.setText(R.string.appupdate_update4);
                    bt_noupdate.setText(R.string.appupdate_update3);
                }
            } else {
                tv_Sversion.setText(R.string.appupdate_Sversion);
                txt_about.setText(R.string.appupdate_about);
                tv_upMessage.setText(dcontext.getString(R.string.appupdate_Message4));
            }
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onClick(View view) {
        try {
            AppUpdateDialog.this.dismiss();
        } catch (Exception e) {
        }
        if (view.getId() == R.id.bt_update) {
            if (appversion != null) {
                updateApk(appversion.getAppDownloadURL());
            }
        }
        if (view.getId() == R.id.bt_noupdate) {
            if (notUpdate != null) {
                notUpdate.todo(null);
            }
        }

    }

    protected void updateApk(String urlAddr) {

        SharePreferenceUtil.getInstance().setIntValue(SharePreferenceUtil.PREFERENCES_ISSHOWUPDATEDIALOG, 1);
        if (mydownDialog != null && !mydownDialog.isShowing()) {
            mydownDialog.show();
        }
        DownAPP(urlAddr, 10000);
    }

    @SuppressWarnings("deprecation")
    private void DownAPP(final String urlAddr, int delayTime) {
        try {
            SharePreferenceUtil.getInstance().setIntValue(SharePreferenceUtil.PREFERENCES_ISSHOWUPDATEDIALOG, 1);
            if (PBDown >= 3) {
                showDownFaild(urlAddr);
                return;
            }

            if (mydownDialog == null) {
                mydownDialog = new ProgressDialog(dcontext, THEME_HOLO_LIGHT);
                mydownDialog.setTitle(R.string.appupdate_download_title);
                mydownDialog.setMessage(dcontext.getString(R.string.appupdate_download_Message1));
                mydownDialog.setCancelable(false);
                mydownDialog.setButton("取消", new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        ISCanCel = true;
                        MCSWebDownLoadProvider.getInstatince().cancelDownFile(att);
                    }
                });
            }
            if (!mydownDialog.isShowing()) {
                mydownDialog.show();
            }

            att = new Attachment();
            att.setAttUri(urlAddr);
            att.setExtName("apk");
            att.setAttName(appversion.getAppCode());

            String dir = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + dcontext.getResources().getString(R.string.app_code);
            SharePreferenceUtil.getInstance().setIntValue(SharePreferenceUtil.PREFERENCES_ISDOWNAPPING, 1);
            MCSWebDownLoadProvider.getInstatince().downLoadFile(dir, att, new MODCallback() {
                @Override
                public void execute(ERRORCODE errcode, Object obj) {
                    String downpath = urlAddr;
                    if (errcode == ERRORCODE.CANCEL || ISCanCel) {
                        return;
                    }
                    if (errcode == ERRORCODE.SUCCESS) {
                        SharePreferenceUtil.getInstance().setIntValue(SharePreferenceUtil.PREFERENCES_ISDOWNAPPING, 0);
                        SharePreferenceUtil.getInstance().remove(SharePreferenceUtil.PREFERENCES_AUTHKEY);
                        mydownDialog.dismiss();
                        File file = new File(obj.toString());
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        Uri uri;
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            uri = FileProvider.getUriForFile(dcontext, dcontext.getPackageName() + ".fileprovider", file);
                        } else {
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            uri = Uri.fromFile(file);
                        }
                        Log.i("bqt", "【Uri】" + uri);
                        intent.setDataAndType(uri, "application/vnd.android.package-archive");
                        dcontext.startActivity(intent);
                        ActivityUtils.getInstance().exit();
                    } else {
                        if (!Tools.isConnected(dcontext)) {
                            showDownFaild(urlAddr);
                        } else if (PBDown < 3) {
                            PBDown++;
                            mydownDialog.setMessage("下载失败，第" + PBDown + "次重试");
                            DownAPP(downpath, 2000);
                        }
                    }
                }

                @Override
                public void onDownloadSize(int size) {
                    if (size == -1) {
                        mydownDialog.setMessage("下载中");
                        return;
                    }
                    SharePreferenceUtil.getInstance().setIntValue(SharePreferenceUtil.PREFERENCES_ISDOWNAPPING, 1);
                    mydownDialog.setMessage("已下载：" + size + "%");
                }
            });
        } catch (Exception e) {
            Log.i("MCLog", "DownAPP异常" + e.toString());
        }
    }

    private void showDownFaild(final String urlAddr) {
        try {
            PBDown = 0;
            try {
                SharePreferenceUtil.getInstance().setIntValue(SharePreferenceUtil.PREFERENCES_ISDOWNAPPING, 0);
                mydownDialog.setMessage(dcontext.getString(R.string.appupdate_download_Message2));
            } catch (Exception e) {
            }
            mydownDialog.dismiss();
            new Builder(dcontext).setTitle(R.string.appupdate_download_Message2).setMessage(dcontext.getString(R.string.appupdate_download_Message3)).setNeutralButton(R.string.appupdate_download_button2, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    DownAPP(urlAddr, 10000);
                }
            }).setNegativeButton(R.string.appupdate_download_button1, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();
        } catch (Exception e) {
        }
    }
}
